
var imageA
var imageB

var ReaderA = new FileReader()
var ReaderB = new FileReader()
$(function(){
    //$(".boximg").hide()
    initUpload()
    initbutton()
    initFileReader()
})

function initUpload(){
    console.log("绑定拖动事件")
    $(".uploadbox").on({
        /*"dragenter": function(e){
            e.preventDefault()
            console.log("有东西在拖动")
        },*/
        "dragover": function(e){
            e.preventDefault()
            e.target.style.borderColor = "blue"
            e.target.style.borderWidth = "5px"
            console.log("文件进来了")
        },
        "dragleave": function(e){
            e.preventDefault()
            e.target.style.borderColor = "cadetblue"
            e.target.style.borderWidth = "medium"
        },
        "drop": function(e){
            e.preventDefault()
            e.stopPropagation()
            id = e.target.getAttribute("id")
            image = $(".boximg"+"#"+id)
            let file = e.originalEvent.dataTransfer.files;
            if (id == "before"){
                ReaderA.readAsDataURL(file[0])
            }else{
                ReaderB.readAsDataURL(file[0])
            }
            image.attr("src",URL.createObjectURL(file[0]))
            e.target.style.borderColor = "cadetblue"
            e.target.style.borderWidth = "medium"
        }
    })
}

function initFileReader(){
    ReaderA.onload = function(e){
        //console.log(ReaderA.result)
        imageA = ReaderA.result
    }

    ReaderB.onload = function(e){
        //console.log(ReaderB.result)
        imageB = ReaderB.result
    }
}

function initbutton(){
    $("button").on({
        "click": function(){
            if (imageA==null||imageB==null){
                return alert("请先输入图片")
            }
            startloading()
            begin = Date.now()
            Url = '/api/infer'
            $.ajax({
                ContentType: "application/json",
                type:'POST',
                dataType:"json",
                url:Url,
                data:JSON.stringify({"task":"CD","img_a":imageA,"img_b":imageB}),
                success:function(res){
                    //console.log("data:image/png;base64,"+res.prod)
                    if (res.code==200){
                        end = Date.now()
                        $(".result").attr("src","data:image/png;base64,"+res.prod)
                        mes = "成功收到结果，系统处理时间："+(res.time*1000).toFixed(0)+"ms; 系统响应时间:"+(end-begin)+"ms"
                        stoploading(mes)
                    }else{
                        mes = "系统出错："+res.err
                        stoploading(mes)
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest, textStatus, errorThrown)
                    mes = "系统出错"+errorThrown
                    stoploading(mes)
                }
            })
        }
    })
}
